#include "BaseConsole.h"
namespace mp_base
{

	BaseConsole::~BaseConsole(){

	}

	void BaseConsole::SendEvent(spConCommand command)
	{

	}
	//need to test
	void BaseConsole::SendEvent(Event::spEvent evnt)
	{
		//Grab string from event
		std::stringstream msgStream;
		msgStream << *evnt;
		std::string msg = msgStream.str();
		msgStream << "\0";

		//Check for no command
		if (msg.length() <= 0){
			//Write invalid input
			//WriteError("Error> BaseConsole::SendEvent \n\t >Invalid Event Type\n");
			return;
		}

		//Lock onto the console
		while (!TryLock()){ Pause(1); }

		//Check if command exists
		//For each command template
		for (ConCmdTemps::iterator it = m_cmdCache->Begin();
			it != m_cmdCache->End(); it++)
		{
			//If command equals one of the templates
			if ( it->GetCommand().compare(msg) )
			{
				//For each listener
				for (list<ConListener>::iterator itx =
					m_conListeners.begin();
					itx != m_conListeners.end(); itx++)
				{
					//If command is linked to a listener
					if ( (*itx) == it->GetListenerID() )
					{
						//Send event to listener
						(*itx).GetListener()(evnt);
						//Write event to console
						std::cout << (*evnt);

						Unlock();
						return;
					}	
				}
				//Write, failed to find listeners
				//WriteError("Error> BaseConsole::SendEvent \n\t >Failed to find listeners for command\n");
			}
		}
		//Write, Failed to load template
		//WriteError("Error> BaseConsole::SendEvent \n\t >Failed to find command\n");

		Unlock();
	}

	istream& BaseConsole::ParseInputFromStream(istream& is)
	{

		return is;
	}



	void BaseConsole::AddConListener(ConListener listener)
	{
		while (!TryLock()){ Pause(1); }
		m_conListeners.push_back(listener);
		Unlock();
	}

	void BaseConsole::RemoveConListener(ConListener listener)
	{
		RemoveConListener(listener.GetID());
	}

	void BaseConsole::RemoveConListener(ulong listener){
		while (!TryLock()){ Pause(1); }
		for (list<ConListener>::iterator it = m_conListeners.begin();
			it != m_conListeners.end(); it++){
			if ((*it) == listener)
			{
				m_conListeners.erase(it);
				break;
			}
		}
		Unlock();
	}

}